package com.zm.base.core.dao.impl;


import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.zm.base.core.dao.IBaseDao;
import com.zm.base.core.exception.BaseException;
import com.zm.base.core.util.BaseDaoUtil;
@Repository("baseDao")
public class BaseDao extends HibernateDaoSupport  implements IBaseDao {
	@Resource(name="sessionFactory")  
	public void setSessionFactoryDI(SessionFactory sessionFactory) {  
	   //调用父类的setSessionFactory方法,注入sessionFactory  
	   super.setSessionFactory(sessionFactory);  
	 }  
	@Override
	public <T> void save(T t) throws BaseException,Exception{
		this.getHibernateTemplate().save(t);
	}

	@Override
	public <T> void update(Class<T> clazz,T t,boolean isAll) throws BaseException, Exception {
		if(true==isAll){
			this.getHibernateTemplate().update(t);
		}else{
			//String tableName=BaseDaoUtil.getTableName(clazz);
			 Map<String, Object> params=BaseDaoUtil.getParams(t);
			 String id=BaseDaoUtil.getPK(clazz);
			 String idValue=params.get(id).toString();
			 params.remove(id);
			 String hql=" ";
			 String setString="";
			 for(Map.Entry<String, Object> entry: params.entrySet()){
				 setString+=entry.getKey()+"="+entry.getValue()+",";
			 }
			 setString=setString.substring(0, setString.length()-1);
			 String className=BaseDaoUtil.getClassName(clazz);
			 hql=" update "+ className+" set "+setString+" where "+id+"="+idValue+"  ";
			 Query query=this.currentSession().createQuery(hql);
			 query.executeUpdate();
		}
	}

	@Override
	public <T> void delete(T t) throws BaseException, Exception {
		this.getHibernateTemplate().delete(t);	
	}

	@Override
	public <T> void delete(Class<T> clazz, Object id) throws BaseException, Exception {
	    String tableName=BaseDaoUtil.getTableName(clazz);
	    String PK=BaseDaoUtil.getPK(clazz);
	    PK=BaseDaoUtil.humpToLine(PK);
	    id=BaseDaoUtil.setParamsInSaveOrUpdate(id);
	    String sql=" delete from "+tableName+" where "+PK+"="+id+" ";
	    this.currentSession().createSQLQuery(sql).executeUpdate();
	}

	@Override
	public <T> T getById(Class<T> clazz, String id) throws BaseException,
			Exception {
		return this.getHibernateTemplate().get(clazz, id);
	}
}
